package com.ml4ai.core.stack.parallel

import java.util

import akka.actor._
import com.ml4ai.core.stack.utils.Toolkit.StringHelper

object RootControlActor {

  var rootActors: java.util.LinkedHashMap[String, RootControlActor] = new util.LinkedHashMap[String, RootControlActor]()

  def apply(root: String) = {
    if (rootActors.containsKey(root)) {
      rootActors.get(root)
    } else {
      val rootActor = new RootControlActor(root)
      rootActors.put(root, rootActor)
      rootActor
    }
  }

}

class RootControlActor(val root: String) {

  val actorSystem = ActorSystem(root)

  val actors = new util.LinkedHashMap[String, ActorRef]

  def apply(props: Props) = {
    val randName = StringHelper.uuid
    val actor = actorSystem.actorOf(props, randName)
    actors.put(randName, actor)
    actor
  }


  def apply(props: Props, name: java.lang.String) = {
    if (actors.containsKey(name)) {
      actors get name
    } else {
      val actor = actorSystem.actorOf(props, name)
      actors.put(name, actor)
      actor
    }
  }

  def apply(name: String) = actors.get(name)

  def getRoot() = root

  def /(name: String) = actors.get(name)

}